package com.chris.getfile.core;

import com.chris.getfile.comm.IoUtil;
import com.chris.getfile.comm.JacksonUtil;
import com.chris.module.okhttp.OkHttpUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 党建云
 */
@Service
public class DjyService {

    @Autowired
    OkHttpUtil okHttpUtil;

    @Autowired
    JacksonUtil jacksonUtil;
    IoUtil io = new IoUtil();

    OkHttpClient client;

    private String file_path="E:\\test\\file";

    String csvFilePath = "E:\\test\\chris.csv"; // 替换为你的CSV文件路径
    List<String[]> csvData = new ArrayList<>();

    /**
     * 下载文件
     */
    public void dowanloadfile() throws IOException {
        loaddata();
        for (int i = 0; i <= 229; i++) {

            for (int j=1;j<5;j++)
            {
                if (csvData.get(i)[j]!=null)
                {
                    dw(csvData.get(i)[0]+"_"+j,csvData.get(i)[j]);
                }
            }



        }

    }

    public void loaddata() throws IOException {


        try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 假设每行有4列，用逗号分隔
                String[] columns = line.split(",");

                // 如果分隔后的列数不足4列，手动添加一个空字符串作为第4列
                if (columns.length <=4) {
                    columns = java.util.Arrays.copyOf(columns, 5); // 扩展数组长度到4
                   // columns[3] = ""; // 设置第4列为默认值或空字符串
               }

                //System.out.println(columns.length);
                if (columns.length == 5) {
                   csvData.add(columns);
                } else {
                   // System.out.println("Skipping invalid line: " + line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 打印读取到的数据
        for (String[] row : csvData) {
          //System.out.println("Column 1: " + row[0] + ", Column 2: " + row[1] + ", Column 3: " + row[2] + ", Column 4: " + row[3]);
        }
    }


    /**
     * 下载文件
     * @param file_name
     * @param dowload_url
     */
    private void dw(String file_name, String dowload_url) {
        //  String url = "https://www.520101.com/down/2310095825849198/2310091624801427";
        if (client == null) {
            // 创建一个 okhttp客户端线程池
            OkHttpClient.Builder builder = new OkHttpClient.Builder();

            //2022-7-15 重要： 当连接失败，尝试重连。组建默认保持5分钟连接，如果下一次连接还是相同url会默认调用原来的连接，但是如果对方客户端已经关闭
            //就会频繁出现  java.io.IOException: unexpected end of stream on ... 的错误
            //  builder.retryOnConnectionFailure(true);
            //  builder.connectionPool(ConnectionPool(Integer.MAX_VALUE, 60, TimeUnit.MINUTES));

            builder.connectTimeout(180, TimeUnit.SECONDS);
            builder.readTimeout(300, TimeUnit.SECONDS);
            builder.writeTimeout(300, TimeUnit.SECONDS);


            client = builder.build();
        }


        // 构建请求对象
        Request request = new Request.Builder().url(dowload_url).get().build();

        // 发起请求得到请求结果
        Response response = null;
        try {
            response = client.newCall(request).execute();


            // 获取请求结果
            ResponseBody responseBody = response.body();
            if (null != responseBody) {
                // 获取文件后缀类型 可以使用 responseBody.contentType() 获取 ContentType，我这边知道这个url文件的类型
                String suffix = ".pdf";
                int j = response.request().url().toString().lastIndexOf(".");
                suffix = response.request().url().toString().substring(j);
                // 创建一个文件
                String filename = file_path + "/" + file_name.replace("/", "-").trim() + suffix;
                File file = new File(filename);

                // 判断目录是否存在，不存在则创建目录

                File parent = new File(file.getParent());
                if (!parent.exists()) {
                    parent.mkdir();
                }

                // 判断文件是否存在, 不存在创建文件
                //if (!file.exists()) { 不管时候存在，新建
                try {
                    try {
                        file.createNewFile();
                    } catch (Exception ee) {
                        filename = file_path  + "/" + file_name + suffix;
                        file = new File(filename);
                        file.createNewFile();
                    }
                    // 获取请求结果输入流
                    InputStream rInputStream = responseBody.byteStream();

                    // 创建读取字节流的byte数组
                    byte[] buffer = new byte[500];

                    int areRead;

                    // 创建文件输出流
                    FileOutputStream outputStream = new FileOutputStream(file);

                    // 使用输入流读取字节，在输出到文件
                    while ((areRead = rInputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, areRead);
                    }
                    rInputStream.close();
                    outputStream.close();

                } catch (IOException e) {
                    // throw new RuntimeException(e);
                    System.out.println("出错"  + " " + e.toString());
                }
                // }
            }
            response.close();
        } catch (IOException e) {
            System.out.println("出错" + " " + e.toString());
            //throw new RuntimeException(e);
        }
    }
}

